<?php

$eurl = "state_naicssector.csv";
if (($handle = fopen ( $eurl, "r" )) !== FALSE) {
    $keys = fgetcsv ( $handle, 4096, ";" );
	$NAICS = array();
	$STATE_DESCRIPTION = array();
	$EESIZE = array();
	$ESTABLISHMENTS = array();
	$EMPLOYMENT = array();
	$PAYROLL = array();
	$AverageSalary = array();
	$PeopleState = array();
	$state = $_POST['state'];
	$naic = $_POST['NAICS'];
	$i = 0;
    while ( ($data = fgetcsv ( $handle, 4096, ";" )) !== FALSE ) {
        $res[] = array_combine($keys, $data);
		if ($res[$i]["STATE DESCRIPTION"] == $_POST['state']) {
			if ($NAICS[count($NAICS)-1]!=$res[$i]["NAICS DESCRIPTION"]) {
				$NAICS[] = $res[$i]["NAICS DESCRIPTION"]; 
			}
		}
		if ($STATE_DESCRIPTION[count($STATE_DESCRIPTION)-1]!=$res[$i]["STATE DESCRIPTION"]) {
			$STATE_DESCRIPTION[] = $res[$i]["STATE DESCRIPTION"]; 
		}
		if ($res[$i]["STATE DESCRIPTION"]==$_POST['state'] && $res[$i]["NAICS DESCRIPTION"]==$_POST['NAICS']  && $res[$i]["ENTERPRISE EMPLOYMENT SIZE"]!=='1:   Total' && $res[$i]["ENTERPRISE EMPLOYMENT SIZE"]!=='5:   <20' && $res[$i]["ENTERPRISE EMPLOYMENT SIZE"]!=='8:   <500') {
			$EESIZE[] = $res[$i]["ENTERPRISE EMPLOYMENT SIZE"]; 
			$ESTABLISHMENTS[] = $res[$i]["NUMBER OF ESTABLISHMENTS"]; 
			$EMPLOYMENT[] = $res[$i]["EMPLOYMENT"]; 
			$PAYROLL[] = $res[$i]["ANNUAL PAYROLL ($1,000)"]; 
		}
		if ($res[$i]["NAICS DESCRIPTION"]==$_POST['NAICS'] && $res[$i]["ENTERPRISE EMPLOYMENT SIZE"]=='1:   Total') {
			$AverageSalary[] = round(preg_replace('/\s+/', '', $res[$i]["ANNUAL PAYROLL ($1,000)"])*1000/preg_replace('/\s+/', '', $res[$i]["EMPLOYMENT"]));
		}
		if ($res[$i]["NAICS DESCRIPTION"]=='Total' && $res[$i]["ENTERPRISE EMPLOYMENT SIZE"]=='1:   Total') {
			$PeopleState[] = $res[$i]["EMPLOYMENT"];
		}
		$i++;
    }
    fclose ($handle);
}
$people = "[['ENTERPRISE EMPLOYMENT SIZE', 'NUMBER OF FIRMS']";
$money = "[['EMPLOYMENT', 'ANNUAL PAYROLL ($1,000)']";
for ($k=0; $k<count($EESIZE); $k++) {
	$people .= ",['".substr($EESIZE[$k],3)."', ".preg_replace('/\s+/', '', $ESTABLISHMENTS[$k])."]";
	$money .= ",['".substr($EESIZE[$k],3)."', ".round(preg_replace('/\s+/', '', $PAYROLL[$k])*1000/preg_replace('/\s+/', '', $EMPLOYMENT[$k]))."]";
}
$people .= "]";
$money .= "]";

$salary = "[['STATE DESCRIPTION', 'AVERAGE SALARY']";
for ($k=0; $k<count($AverageSalary); $k++) {
	$salary .= ",['".$STATE_DESCRIPTION[$k]."', ".$AverageSalary[$k]."]";
}
$salary .= "]";

$employment = "[['STATE DESCRIPTION', 'EMPLOYMENT']";
for ($k=0; $k<count($PeopleState); $k++) {
	$employment .= ",['".$STATE_DESCRIPTION[$k]."', ".preg_replace('/\s+/', '', $PeopleState[$k])."]";
}
$employment .= "]";

//echo $employment;

?>